﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using RibbonEditor.Managers;
using Microsoft.Xrm.Sdk.Metadata;

namespace RibbonEditor.Forms.Solutions
{
    public partial class CreateSolutionDialog : Form
    {
        IOrganizationService innerService;
        MetadataManager innerMetadataManager;
        internal Guid publisherId;

        Entity createdSolution;

        public Entity CreatedSolution
        {
            get { return createdSolution; }
            set { createdSolution = value; }
        }

        public CreateSolutionDialog(IOrganizationService service, MetadataManager mManager)
        {
            InitializeComponent();
            this.innerService = service;
            this.innerMetadataManager = mManager;
            this.FillEntities();
        }

        private void FillEntities()
        {
            foreach (EntityMetadata emd in this.innerMetadataManager.EntityCache)
            {
                if (emd.IsCustomizable.Value && emd.DisplayName.UserLocalizedLabel != null)
                {
                    ListViewItem item = new ListViewItem()
                    {
                        Text = emd.DisplayName.UserLocalizedLabel.Label,
                        Tag = emd
                    };

                    this.lvSelectedEntities.Items.Add(item);
                }
            }
        }
       
        private void btnValidate_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.strDisplayName.Value.Length == 0 || this.strName.Value.Length == 0
                || this.rcPublisher.Value.Length == 0 || this.strVersion.Value.Length == 0)
                {
                    MessageBox.Show(this, "Please fill all required fields! ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    Entity solution = new Entity("solution");
                    solution["uniquename"] = this.strName.Value;
                    solution["friendlyname"] = this.strDisplayName.Value;
                    solution["publisherid"] = new EntityReference("publisher", this.publisherId);
                    solution["description"] = this.txtDescription.Text;
                    solution["version"] = this.strVersion.Value;

                    Guid solutionId = this.innerService.Create(solution);
                    solution["id"] = solutionId;

                    if (this.chkAddApplicationRibbon.Checked)
                    {
                        AddSolutionComponentRequest request = new AddSolutionComponentRequest()
                        {
                            ComponentType = 50, // Application Ribbon
                            SolutionUniqueName = solution["uniquename"].ToString(),
                            ComponentId = RetrieveRibbonCustomization(innerService).Id
                        };

                        this.innerService.Execute(request);
                    }

                    foreach (ListViewItem item in this.lvSelectedEntities.CheckedItems)
                    {
                        AddSolutionComponentRequest request = new AddSolutionComponentRequest()
                        {
                            ComponentType = 1, // Entity
                            SolutionUniqueName = solution["uniquename"].ToString(),
                            ComponentId = ((EntityMetadata)item.Tag).MetadataId.Value
                        };

                        this.innerService.Execute(request);
                    }

                    this.createdSolution = solution;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(this, "Error while creating solution: " + error.Message,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnSelectPublisher_Click(object sender, EventArgs e)
        {
            Publishers.PublisherPicker ppDialog = new Publishers.PublisherPicker(this.innerService);
            ppDialog.StartPosition = FormStartPosition.CenterParent;

            if (ppDialog.ShowDialog() == DialogResult.OK)
            {
                this.publisherId = (Guid)ppDialog.SelectedPublisher["publisherid"];
                this.rcPublisher.Value= ppDialog.SelectedPublisher["friendlyname"].ToString();
            }
        }

        public static Entity RetrieveRibbonCustomization(IOrganizationService innerService)
        {
            ConditionExpression ce = new ConditionExpression();
            ce.AttributeName = "entity";
            ce.Operator = ConditionOperator.Null;

            ConditionExpression ce2 = new ConditionExpression();
            ce2.AttributeName = "ismanaged";
            ce2.Operator = ConditionOperator.Equal;
            ce2.Values.Add(false);

            FilterExpression fe = new FilterExpression();
            fe.AddCondition(ce);
            fe.AddCondition(ce2);


            QueryExpression qe = new QueryExpression("ribboncustomization");
            qe.ColumnSet = new ColumnSet(true);
            qe.Criteria = fe;

            EntityCollection col = innerService.RetrieveMultiple(qe);

            if (col.Entities.Count == 1)
            {
                return col.Entities[0];
            }
            else
            {
                throw new Exception("More than one unmanaged ribbon found!");
            }
        }

    }
}
